import axios from "axios";
import { Loading, Message, MessageBox } from "ccui";
import store from "../store";
import { addUrlPerFix } from "@/basa/utils";

import Cookies from "js-cookie";
import Vue from "vue";
import { getArgs } from "@/basa/utils";
axios.defaults.withCredentials = true;

const service = axios.create({
  baseURL: addUrlPerFix(process.env.VUE_APP_BASE_URL), // api 的 base_url
  timeout: 1000 * 60 // request timeout
});

let loadingObj;
let pageLoading = "";

// 请求拦截器
service.interceptors.request.use(
  config => {
    // requestConfig = config;
    config.headers.Authorization = Cookies.get("access_token") || "";
    config.headers.APP_TOKEN = localStorage.appToken || "";

    if (config.method === 'post') {
      // 加数据变动loading
      if (typeof config.data === "object" && config.data.isShowLoading === true) {
        delete config.data.isShowLoading;
        store.commit(
          "SET_LOADINGMESSAGE",
          config.data.loadingMessage || "处理中,请稍等..."
        );
        delete config.data.loadingMessage;
        loadingObj = Loading.service({
          lock: true,
          text: store.getters.loadingMessage,
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.2)",
          customClass: "ccui-custom-loading"
        });
      }
      // 加页面列表loading
      if (
        typeof config.data === "object" &&
        config.data.isShowPageLoading === true
      ) {
        pageLoading = config.url;
        store.dispatch("setPageLoadingEnable", true);
        store.dispatch("setPageLoading", true);
        delete config.data.isShowPageLoading;
      }

      // 获取agentId
      config.data.agentId = getArgs("a");

      if (store.state.user.userDetal) {
        const userInfo = store.state.user.userDetal;
        config.data.baseAppId = userInfo.appId;
      }
    } else {
      pageLoading = config.url;
      store.dispatch("setPageLoadingEnable", true);
      store.dispatch("setPageLoading", true);
    }
    return config;
  },
  error => {
    // Do something with request error
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 关闭数据变动loading
    if (loadingObj !== undefined) {
      loadingObj.close();
      loadingObj = undefined;
    }
    // 关闭页面列表loading
    if (
      store.state.app.pageLoading.pageLoadingStatus &&
      response.config.url === pageLoading
    ) {
      Vue.nextTick(() => {
        store.dispatch("setPageLoading", false);
      });
    }
    // 请求正常
    return response;
  },
  error => {
    // 系统错误处理
    if (loadingObj) {
      loadingObj.close();
      loadingObj = undefined;
    }
    let message =
      error.code === "ECONNABORTED"
        ? `<i class="el-icon-warning"></i>网络请求超时`
        : `<i class="el-icon-warning"></i>系统错误，请<a class="ccui-message-box-custom-link">联系管理员</a>`;
    Message.closeAll();
    MessageBox.alert(message, "提示", {
      distinguishCancelAndClose: true,
      dangerouslyUseHTMLString: true,
      customClass: "ccui-message-box-custom"
    });

    return Promise.reject(error.data);
  }
);

export default service;
